package com.base.activity;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.base.BaseApplication;
import com.base.R;
import com.base.http.common.BaseHttpClient;
import com.base.http.common.BaseParams;
import com.base.http.entity.METHOD;
import com.base.http.listener.HttpCallback;
import com.base.utils.ActivityContainer;
import com.base.utils.CropUtil;
import com.base.utils.ImageUtil;

import java.io.File;

/**
 * 页面基础类
 * Created by Android on 2017/3/7 0007.
 */

public abstract class BaseActivity extends AppCompatActivity {

    public Context mContext;
    public Click click;
    public HttpClick httpClick;
    public BaseParams mParams;
    public ActivityContainer mActivityContainer;
    private BaseApplication app;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(NetworkReceiver);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        click = new Click();
        httpClick = new HttpClick();
        if (mParams == null) {
            mParams = new BaseParams();
        }
        app = (BaseApplication) getApplication();
        mActivityContainer = ActivityContainer.getInstance();
        appOpen();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(NetworkReceiver, intentFilter);

        initView(savedInstanceState);
        initData(savedInstanceState);
        initListener();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            appFinish();
        }
        return false;
    }

    /**
     * 关闭页面
     */
    public void appFinish() {
        super.finish();
        overridePendingTransition(
                R.anim.push_right_in, R.anim.push_right_out);
        mActivityContainer.removeActivity(this);
    }

    /**
     * 打开页面
     */
    public void appOpen() {
        overridePendingTransition(
                R.anim.push_left_in, R.anim.push_left_out);
        mActivityContainer.addActivity(this);
    }

    /**
     * 初始化界面
     *
     * @param bundle
     */
    protected abstract void initView(Bundle bundle);

    /**
     * 初始化数据
     *
     * @param bundle
     */
    protected abstract void initData(Bundle bundle);

    /**
     * 初始化监听
     */
    protected abstract void initListener();

    /**
     * click事件
     *
     * @param id
     */
    public void setOnClickListener(int id) {
        if (click == null) {
            click = new Click();
        }
        findViewById(id).setOnClickListener(click);
    }

    /**
     * 重写click事件
     */
    public class Click implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            treatClickEvent(v.getId());
            treatClickEvent(v);
        }
    }

    public void treatClickEvent(int id) {

    }

    public void treatClickEvent(View view) {

    }

    /**
     * 替换fragment
     */
    public void replaceContent(int containerViewId, Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
        transaction.replace(containerViewId, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

    /**
     * toast提示框
     *
     * @param str
     */
    public void showToast(String str) {
        Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
    }

    public void showToast(int resId) {
        Toast.makeText(mContext, resId, Toast.LENGTH_SHORT).show();
    }

    /**
     * 不带标题的提示框
     *
     * @param message
     * @param clickListener
     */
    public void showDialog(String message, DialogInterface.OnClickListener clickListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage(message);
        builder.setPositiveButton(R.string.sumbit, clickListener);
        builder.setNegativeButton(R.string.cancel, null);
        builder.show();
    }

    /**
     * 带标题的提示框
     *
     * @param title
     * @param message
     * @param clickListener
     */
    public void showDialog(String title, String message, DialogInterface.OnClickListener clickListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(R.string.sumbit, clickListener);
        builder.setNegativeButton(R.string.cancel, null);
        builder.show();
    }

    public final static int SELECT_GALLERY = 0x000010;
    public final static int SELECT_CAMERA = 0x000020;
    public final static int CROP_PHOTO = 0x000030;

    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x04;
    private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x05;
    public File fileUri =
            new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    public File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    public Uri imageUri;
    public static Uri cropImageUri;

    /**
     * 自动获取相机权限
     */
    public void autoObtainCameraPermission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                showToast("您已经拒绝过一次");
            }
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
        } else {//有权限直接调用系统相机拍照
            imageUri = Uri.fromFile(fileUri);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                imageUri = FileProvider.getUriForFile(mContext, "com.base.provider", fileUri);//通过FileProvider创建一个content类型的Uri
            }
            tackPicture();
        }
    }

    /**
     * 自动获取sdk权限
     */

    private void autoObtainStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSIONS_REQUEST_CODE);
        } else {
//            Intent intent1 = new Intent(Intent.ACTION_PICK, null);
//            intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//            startActivityForResult(intent1, SELECT_GALLERY);
            openPic();
        }

    }

    private void tackPicture() {
        //调用系统相机
        Intent intentCamera = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intentCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        }
        intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        //将拍照结果保存至photo_file的Uri中，不保留在相册中
        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intentCamera, SELECT_CAMERA);// 采用ForResult打开
    }

    private void openPic() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, SELECT_GALLERY);
    }

    /**
     * 选择调用本地相册，还是手机拍照
     */
    public void showImgTypeDialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        final android.app.AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_select_photo, null);
        TextView tv_select_gallery = (TextView) view.findViewById(R.id.dialog_select_gallery);
        TextView tv_select_camera = (TextView) view.findViewById(R.id.dialog_select_camera);
        tv_select_gallery.setOnClickListener(new View.OnClickListener() {// 在相册中选取
            @Override
            public void onClick(View v) {
//                Intent intent1 = new Intent(Intent.ACTION_PICK, null);
//                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//                startActivityForResult(intent1, SELECT_GALLERY);
                autoObtainStoragePermission();
                dialog.dismiss();
            }
        });
        tv_select_camera.setOnClickListener(new View.OnClickListener() {// 调用照相机
            @Override
            public void onClick(View v) {
//                Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                intent2.putExtra(MediaStore.EXTRA_OUTPUT,
//                        Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "head.jpg")));
//                startActivityForResult(intent2, SELECT_CAMERA);// 采用ForResult打开
                autoObtainCameraPermission();
                dialog.dismiss();
            }
        });
        dialog.setView(view);
        dialog.show();
    }

    /**
     * 调用系统的裁剪功能
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_PHOTO);
    }

    public void cropImageUri(Uri orgUri, Uri desUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(orgUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("scale", true);
        //将剪切的图片保存到目标Uri中
        intent.putExtra(MediaStore.EXTRA_OUTPUT, desUri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, CROP_PHOTO);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case CAMERA_PERMISSIONS_REQUEST_CODE: //调用系统相机申请拍照权限回调
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    imageUri = Uri.fromFile(fileUri);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        imageUri = FileProvider.getUriForFile(mContext, "com.base.provider", fileUri);//通过FileProvider创建一个content类型的Uri
                    }
                    tackPicture();
                } else {
                    showToast("请允许打开相机！");
                }
                break;
            case STORAGE_PERMISSIONS_REQUEST_CODE://调用系统相册申请Sdcard权限回调
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    Intent intent1 = new Intent(Intent.ACTION_PICK, null);
//                    intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//                    startActivityForResult(intent1, SELECT_GALLERY);
                    openPic();
                } else {
                    showToast("请允许打操作SDCard！");
                }
                break;
        }
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        switch (requestCode) {
//            case SELECT_GALLERY:
//                if (resultCode == RESULT_OK) {
////                    cropPhoto(data.getData());
//                    cropImageUri = Uri.fromFile(fileCropUri);
//                    Uri newUri = Uri.parse(CropUtil.getPath(this, data.getData()));
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                        newUri = FileProvider.getUriForFile(this, "com.base.provider", new File(newUri.getPath()));
//                    }
//                    cropImageUri(newUri, cropImageUri);
//                }
//                break;
//            case SELECT_CAMERA:
//                if (resultCode == RESULT_OK) {
////                    File temp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
////                    cropPhoto(Uri.fromFile(temp));
//                    cropImageUri = Uri.fromFile(fileCropUri);
//                    cropImageUri(imageUri, cropImageUri);
//                }
//                break;
//        }
//    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return this.getString(R.string.can_not_find_version_name);
        }
    }

    /**
     * 初始化请求参数
     */
    protected void initParameter() {
        if (mParams == null) {
            mParams = new BaseParams();
        } else {
            mParams.clear();
        }
    }

    /**
     * http相关
     */
    public class HttpClick extends HttpCallback {

        @Override
        public void success(String content, BaseHttpClient client, Object parse) {
            onSuccess(content, client, parse);
        }

        @Override
        public void error(Throwable error, BaseHttpClient client) {
            onError(error, client);
        }
    }

    /**
     * get请求
     *
     * @param url
     * @param params
     * @param cls
     */
    public void sendGetRequest(String url, String urlType, BaseParams params, Class<?> cls) {
        BaseHttpClient.newBuilder().url(url)
                .urlIdentifier(urlType)
                .setBaseParams(params)
                .setParse(cls)
                .method(METHOD.GET)
                .build().execute(httpClick);
    }

    /**
     * get加密请求
     *
     * @param url
     * @param params
     * @param cls
     */
    public void sendEncryptGetRequest(String url, String urlType, BaseParams params, Class<?> cls) {
        BaseHttpClient.newBuilder().url(url)
                .urlIdentifier(urlType)
                .setBaseParams(params)
                .setParse(cls)
                .method(METHOD.GET)
                .setEncrypt(true)
                .build().execute(httpClick);
    }

    /**
     * post请求
     *
     * @param url
     * @param cls
     */
    public void sendPostRequest(String url, String urlType, BaseParams params, Class<?> cls) {
        BaseHttpClient.newBuilder().url(url)
                .urlIdentifier(urlType)
                .setBaseParams(params)
                .setParse(cls)
                .method(METHOD.POST_FORM)
                .build().execute(httpClick);
    }

    /**
     * post加密请求
     *
     * @param url
     * @param params
     * @param cls
     */
    public void sendEncryptPostRequest(String url, String urlType, BaseParams params, Class<?> cls) {
        BaseHttpClient.newBuilder().url(url)
                .urlIdentifier(urlType)
                .setBaseParams(params)
                .setParse(cls)
                .method(METHOD.POST_FORM)
                .setEncrypt(true)
                .build().execute(httpClick);
    }

    /**
     * 成功返回
     *
     * @param content
     * @param client
     * @param parse
     */
    protected abstract void onSuccess(String content, BaseHttpClient client, Object parse);

    /**
     * 失败返回
     */
    protected abstract void onError(Throwable error, BaseHttpClient client);


    /**
     * 检测网络是否连接
     */
    private boolean NetworkAvailable() {
        try {
            Thread.sleep(600);
            //得到网络连接信息
            ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            if (manager != null) {
                // 获取NetworkInfo对象
                NetworkInfo networkInfo = manager.getActiveNetworkInfo();
                //去进行判断网络是否连接
                if (networkInfo != null || networkInfo.isAvailable()) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private BroadcastReceiver NetworkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (NetworkAvailable()) {
                intentState(true);
            } else {
                intentState(false);
            }
        }
    };

    protected abstract void intentState(boolean state);

}
